<template>
  <div>
    <h2>表单数据校验</h2>
    <form @submit.prevent="submitForm">
      <div>
        <label for="username">用户名：</label>
        <input type="text" id="username" v-model="username" required>
        <span v-if="!isUsernameValid" style="color: red;">用户名不能为空</span>
      </div>
      <div>
        <label for="password">密码：</label>
        <input type="password" id="password" v-model="password" required>
        <span v-if="!isPasswordValid" style="color: red;">密码不能为空</span>
      </div>
      <button type="submit">提交</button>
    </form>
  </div>
</template>

<script>
export default {
  data() {
    return {
      username: '',
      password: '',
      isUsernameValid: true,
      isPasswordValid: true
    };
  },
  methods: {
    submitForm() {
      // 校验用户名和密码
      this.isUsernameValid = this.username.trim() !== '';
      this.isPasswordValid = this.password.trim() !== '';

      // 如果用户名和密码都有效，则提交表单
      if (this.isUsernameValid && this.isPasswordValid) {
        // 提交表单数据
        console.log('提交表单：', this.username, this.password);
        // 这里可以调用发送表单数据的方法
      }
    }
  }
};
</script>